#Boa:Dialog:Ventas

import wx
import wx.grid
import utiles
import consultasBD

def create(parent):
    return Ventas(parent)

[wxID_VENTAS, wxID_VENTASGRID1, wxID_VENTASGRID2, wxID_VENTASINCLIENTANOMBRE, 
 wxID_VENTASINFECHA, wxID_VENTASINNOMBRE, wxID_VENTASINNROFACTURA, 
 wxID_VENTASINTOTALFACTURA, wxID_VENTASSPINBUTTON1, wxID_VENTASSTATICTEXT1, 
 wxID_VENTASSTATICTEXT2, wxID_VENTASSTATICTEXT3, wxID_VENTASSTATICTEXT4, 
 wxID_VENTASSTATICTEXT5, 
] = [wx.NewId() for _init_ctrls in range(14)]

class Ventas(wx.Dialog):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Dialog.__init__(self, id=wxID_VENTAS, name='Ventas', parent=prnt,
              pos=wx.Point(227, 181), size=wx.Size(745, 448),
              style=wx.DEFAULT_DIALOG_STYLE, title='LISTAR VENTAS')
        self.SetClientSize(wx.Size(729, 412))

        self.spinButton1 = wx.SpinButton(id=wxID_VENTASSPINBUTTON1,
              name='spinButton1', parent=self, pos=wx.Point(8, 8),
              size=wx.Size(104, 17), style=wx.SP_HORIZONTAL)
        self.spinButton1.Bind(wx.EVT_SPIN_UP, self.OnSpinUp,
              id=wxID_VENTASSPINBUTTON1)
        self.spinButton1.Bind(wx.EVT_SPIN_DOWN, self.OnSpinDown,
              id=wxID_VENTASSPINBUTTON1)

        self.inClientaNombre = wx.TextCtrl(id=wxID_VENTASINCLIENTANOMBRE,
              name='inClientaNombre', parent=self, pos=wx.Point(456, 8),
              size=wx.Size(56, 21), style=0, value='')
        self.inClientaNombre.SetEditable(False)

        self.grid1 = wx.grid.Grid(id=wxID_VENTASGRID1, name='grid1',
              parent=self, pos=wx.Point(16, 40), size=wx.Size(696, 232),
              style=0)
        self.grid1.EnableEditing(False)
        self.grid1.Enable(True)

        self.grid2 = wx.grid.Grid(id=wxID_VENTASGRID2, name='grid2',
              parent=self, pos=wx.Point(8, 280), size=wx.Size(464, 128),
              style=0)
        self.grid2.EnableEditing(False)

        self.staticText1 = wx.StaticText(id=wxID_VENTASSTATICTEXT1,
              label='IDCliente:', name='staticText1', parent=self,
              pos=wx.Point(408, 8), size=wx.Size(49, 13), style=0)

        self.innrofactura = wx.TextCtrl(id=wxID_VENTASINNROFACTURA,
              name='innrofactura', parent=self, pos=wx.Point(320, 8),
              size=wx.Size(64, 21), style=0, value='')
        self.innrofactura.SetEditable(True)
        self.innrofactura.Bind(wx.EVT_KILL_FOCUS, self.OnInnrofacturaKillFocus)

        self.staticText2 = wx.StaticText(id=wxID_VENTASSTATICTEXT2,
              label='Factura:', name='staticText2', parent=self,
              pos=wx.Point(272, 8), size=wx.Size(42, 13), style=0)

        self.staticText3 = wx.StaticText(id=wxID_VENTASSTATICTEXT3,
              label='Fecha:', name='staticText3', parent=self, pos=wx.Point(136,
              8), size=wx.Size(34, 13), style=0)

        self.infecha = wx.TextCtrl(id=wxID_VENTASINFECHA, name='infecha',
              parent=self, pos=wx.Point(176, 8), size=wx.Size(72, 21), style=0,
              value='')
        self.infecha.SetEditable(False)

        self.intotalfactura = wx.TextCtrl(id=wxID_VENTASINTOTALFACTURA,
              name='intotalfactura', parent=self, pos=wx.Point(608, 288),
              size=wx.Size(100, 21), style=0, value='')
        self.intotalfactura.SetEditable(False)

        self.staticText4 = wx.StaticText(id=wxID_VENTASSTATICTEXT4,
              label='Total Factura:', name='staticText4', parent=self,
              pos=wx.Point(528, 296), size=wx.Size(69, 13), style=0)

        self.staticText5 = wx.StaticText(id=wxID_VENTASSTATICTEXT5,
              label='Nombre:', name='staticText5', parent=self,
              pos=wx.Point(528, 8), size=wx.Size(42, 13), style=0)

        self.innombre = wx.TextCtrl(id=wxID_VENTASINNOMBRE, name='innombre',
              parent=self, pos=wx.Point(576, 8), size=wx.Size(136, 21), style=0,
              value='')

    def __init__(self, parent):
        self._init_ctrls(parent)
        self.padre = parent
        self.sucursal = self.padre.sucursalNro
        
        self.cantidad_facturas = self._cantidad_facturas()
        self.id_factura = None
        self.orden_factura = 0
        
        self.grillafactura()
        self.init_grillaFacturaPagos()
        self._cargar_factura(self.orden_factura)
    
    
    def _cargar_factura(self, orden_factura):
        from pprint import pprint
        print "ORDEEEEEEEEEN ", orden_factura
        sql_ultima = "  SELECT *, fecha FROM ventas c ORDER BY fecha DESC,nrofactura DESC "
        resultados = consultasBD.ordenCrudaDict(sql_ultima)
        
        factura = resultados[int(orden_factura)]
        
        self.infecha.ChangeValue(str(factura['fecha']))
        self.inClientaNombre.ChangeValue(str(factura['idcliente']))
        self.innrofactura.ChangeValue(str(factura['nrofactura']))
        
            
        SQL3= "SELECT nombre from cliente WHERE idcliente='%s'" % (str(factura['idcliente']))
        print SQL3
        nombreClienta = consultasBD.ordenCrudaDict(SQL3)
        
        try:
            self.innombre.ChangeValue(str(nombreClienta[0]["nombre"] ))
        except:
            self.innombre.ChangeValue("")
                
##        utiles.cargar_fecha(factura['fecha'], self.infechaingreso)
##        utiles.cargar_fecha(factura['fechafactura'], self.infechafactura)
                
        self.id_factura = factura['idventa']
        
        self._limpiar_grilla()
        
        #CARGO LOS PRODUCTOS ***************************
        sql_items = "SELECT * FROM ventastieneproductos vp JOIN ventas v ON vp.idticket = v.idventa WHERE vp.idticket = '%s' " % factura['idventa']
        print sql_items
        items = consultasBD.ordenCrudaDict(sql_items)
        for i, item in enumerate(items):
            ptc=str(item['ptc'])
            
            self.grid1.SetCellValue(i, 0, str(item["ptc"])) #descri
            self.grid1.SetCellValue(i, 1, str(item["ptc"])) #descri
            self.grid1.SetCellValue(i, 2, str(item["descri"])) #descri
            self.grid1.SetCellValue(i, 3, str(item["talle"])) #talle
            self.grid1.SetCellValue(i, 4, str(item["color"])) #color
            self.grid1.SetCellValue(i, 5, str(item["cantidad"])) #cantidad
            self.grid1.SetCellValue(i, 6, str(item["preciolista"])) #P. Unitario
            self.grid1.SetCellValue(i, 7, str("")) #Subtotal
            self.grid1.SetCellValue(i, 8, str(item["descuento"]))           #descuento
            self.grid1.SetCellValue(i, 9, str(item["preciofinal"])) #Total
        
        self.intotalfactura.ChangeValue(str(item["totalfactura"]))

        #* CARGO LA FORMA DE PAGO
        sql_items2 = "SELECT vp.idventa as idventa,vp.idformapagos as idformapago,vp.descrivalor as descrivalor,vp.cuotas as cuotas,vp.monto as monto, vp.monto as total FROM ventastienepagos vp JOIN ventas v ON vp.idventa = v.idventa WHERE vp.idventa = '%s' UNION SELECT vcte.idventa as idventa,vcte.idformapagos as idformapago,vcte.descripcion  as descrivalor,vcte.cuota as cuotas, vcte.montocuota  as monto, SUM(vcte.montocuota) as total FROM vtas_ctasctes vcte JOIN ventas v ON vcte.idventa = v.idventa  WHERE vcte.idventa = '%s' GROUP BY vcte.idventa " % (factura['idventa'],factura['idventa'])
        print sql_items2
        items2 = consultasBD.ordenCrudaDict(sql_items2)
        
        for i, item in enumerate(items2):
            
            self.grid2.SetCellValue(i, 0, str(item["idformapago"])) #descri
            self.grid2.SetCellValue(i, 1, str(item["descrivalor"])) #descri
            self.grid2.SetCellValue(i, 2, str(item["cuotas"])) #descri
            self.grid2.SetCellValue(i, 3, str(item["monto"])) #talle
            self.grid2.SetCellValue(i, 4, str(item["total"])) #color

        
    
    
    def _limpiar_grilla(self):
        for col in range(11):
            for fil in range(30):
                self.grid1.SetCellValue(fil, col, "")
        
        for col in range(5):
            for fil in range(4):
                self.grid2.SetCellValue(fil, col, "")
    
    
    def _cantidad_facturas(self):
        sql = "SELECT count(*) as cantidad FROM ventas"
        resultados = consultasBD.ordenCrudaDict(sql)
        return resultados[0]['cantidad']
    
    def _orden_factura(self, id_factura):
        consultasBD.executa(None, "SET @row = -1")
        sql = "SELECT * FROM ( SELECT c.*, @row := @row + 1 AS fila FROM ventas c ORDER BY fecha DESC,nrofactura DESC ) as m WHERE m.nrofactura = '%s'" % id_factura
        print sql
        resultados = consultasBD.ordenCrudaDict(sql, "SET @row = -1")        
        
        if len(resultados) == 0:
            print "FACTURA NO ENCONTRADA"
            mensaje = wx.MessageDialog(self, "Factura No Encontrada", "Error", style=wx.OK,pos = wx.DefaultPosition)
            mensaje.ShowModal()            
            return 0
        else:
            return resultados[0]['fila']        
    
    def grillafactura(self):
        columnas =['  PTC  ','Codigo','Descripcion        ','Talle','Color','Cant.','Unitario $','Sub-Total $','Desc. %','Total $','Modista']
        self.grid1.CreateGrid(30,len(columnas))
          
        for i,col in enumerate(columnas): 
            self.grid1.SetColLabelValue(i, col)
            
        self.grid1.AutoSizeColumn(0,True)
        self.grid1.AutoSizeRow(0,True)
        self.grid1.AutoSizeColumn(1,True)
        self.grid1.AutoSizeColumn(2,True)
        self.grid1.AutoSizeColumn(3,True)
        self.grid1.AutoSizeColumn(4,True)
        self.grid1.AutoSizeColumn(5,True)
        self.grid1.AutoSizeColumn(6,True)
        self.grid1.AutoSizeColumn(7,True)
        self.grid1.AutoSizeColumn(8,True)
        self.grid1.AutoSizeColumn(9,True)
        self.grid1.AutoSizeColumn(10,True)
        
        #self.grid1.SetColSize(0,95)
        #self.grid1.SetColSize(1,120)
        #self.grid1.DisableDragColSize()
        #self.grid1.DisableDragRowSize()
        self.total = "" 
        for x in xrange(30):
            for i in xrange(len(columnas)):
                if i not in (0,1,5,8,10):
                    self.grid1.SetReadOnly(x,i,True)


    def init_grillaFacturaPagos(self):
        #Conf. GRilla nro. 2 de forma de pago
        cantidadRenglones = 4
        self.grid2.CreateGrid(cantidadRenglones,5)      
        columnas =['Forma','Descripcion','Cuotas','Valor Cuota','Total']
        for i in range(len(columnas)-1,-1,-1): 
            self.grid2.SetColLabelValue(i, columnas[i])
        self.grid2.AutoSizeColumn(0,True)
        self.grid2.AutoSizeColumn(1,True)
        self.grid2.AutoSizeColumn(2,True)
        self.grid2.AutoSizeColumn(3,True)
        self.grid2.SetColSize(1,100)
        #self.grid2.DisableDragColSize()
        #self.grid2.DisableDragRowSize()
        for x in xrange(cantidadRenglones):
            for i in xrange(5):
                if i not in (0,4):
                    self.grid2.SetReadOnly(x,i,True)
    
    def OnSpinUp(self, event):
        self.orden_factura -= 1
        if self.orden_factura < 0:
            self.orden_factura = self.cantidad_facturas - 1
        
        self._cargar_factura(self.orden_factura)
        print "self.orden_factura ", self.orden_factura
        event.Skip()

    def OnSpinDown(self, event):
        print "DOWN"
        print self.cantidad_facturas
        self.orden_factura = (self.orden_factura + 1) % self.cantidad_facturas
        self._cargar_factura(self.orden_factura)
        print "self.orden_factura ", self.orden_factura
        event.Skip()
        
    def OnInnrofacturaKillFocus(self, event):
        self.orden_factura = self._orden_factura(self.innrofactura.Value)
        print "OOOORRRRRDDDDEEEEENNNN", self.orden_factura
        
        self._cargar_factura(self.orden_factura)
        event.Skip()        

